require 'socket'
require 'thread'
require 'pp'


class HTTPServerStub
  attr_accessor :port, :thread
        
  def initialize(response, &block)
    server = TCPServer.new('127.0.0.1', 0)
    self.port = server.addr[1]
    
    self.thread = Thread.new(server, block) do |server, blk|
      sess = server.accept
      request = ''
      while (line = sess.readline).strip != ''
        request << line
      end

      sess.write(response)
      sess.close
      
      blk.call(request)
    end
  end
  def join_thread
    self.thread.join
  end
end


if __FILE__ == $0
  
  response = <<EOS
HTTP/1.x 200 OK
Connection: close
Date: Mon, 21 Jul 2008 23:54:13 GMT
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 0
EOS
  
  server = HTTPServerStub.new(response) do |request|
    puts
    puts "The server received: #{request}"
    puts
  end
  
  socket = TCPSocket.new("127.0.0.1", server.port)  
  
  socket.write(<<EOS)
POST /api/send_message HTTP/1.1
Host: zeepmobile.com
Authorization: Zeep cef7a046258082993759bade995b3ae8:XGPPx8+Me8RBoEUTPO6LSiSLDn4=
Date: Mon, 21 Jul 2008 23:51:52 GMT
Content-Type: application/x-www-form-urlencoded
Content-Length: 70
user_id=1234&body=Art+thou+not+Romeo%2C+and+a+Montague%3F

EOS

  puts
  puts "The server sent: #{socket.read}"
  puts
  
  server.join_thread
end